<template>
  <view class="register-page">
    <view class="welcome">
      <text class="title">新用户注册</text>
      <text class="subtitle">填写以下信息完成注册</text>
    </view>
    
    <view class="register-container">
      <!-- 注册表单 -->
      <view class="form-section">
        <view class="form-item">
          <text class="label">昵称</text>
          <input
            v-model="nickname"
            class="input"
            type="text"
            placeholder="请输入昵称"
            maxlength="20"
            @input="validateNickname"
            @blur="validateNickname"
          />
          <text class="error" v-if="nicknameError">{{ nicknameError }}</text>
        </view>

        <view class="form-item">
          <text class="label">手机号</text>
          <input
            v-model="phone"
            class="input"
            type="number"
            placeholder="请输入11位手机号"
            maxlength="11"
            @blur="validatePhone"
            @input="validateForm"
          />
          <text class="error" v-if="phoneError">{{ phoneError }}</text>
        </view>

        <!-- 地区选择 -->
        <view class="form-item">
          <text class="label">地区(可选)</text>
          <picker 
            mode="region" 
            @change="handleRegionChange"
            :value="region"
            class="picker"
          >
            <view class="picker-view">
              {{ region[0] && region[1] && region[2] ? region.join(' ') : '请选择地区' }}
            </view>
          </picker>
        </view>

        <!-- 邮箱输入 -->
        <view class="form-item">
          <text class="label">邮箱</text>
          <input
            v-model="email"
            class="input"
            type="text"
            placeholder="请输入邮箱"
            @blur="validateEmail"
            @input="validateForm"
          />
          <text class="error" v-if="emailError">{{ emailError }}</text>
        </view>

        <view class="form-item">
          <text class="label">密码</text>
          <input
            v-model="password"
            class="input"
            type="password"
            placeholder="请设置密码"
            @blur="validatePassword"
            @input="validateForm"
          />
          <text class="error" v-if="passwordError">{{ passwordError }}</text>
        </view>

        <view class="form-item">
          <text class="label">确认密码</text>
          <input
            v-model="confirmPassword"
            class="input"
            type="password"
            placeholder="请再次输入密码"
            @blur="validateConfirmPassword"
            @input="validateForm"
          />
          <text class="error" v-if="confirmPasswordError">{{ confirmPasswordError }}</text>
        </view>

        <view class="agreement">
          <checkbox-group @change="handleAgreementChange">
            <checkbox :checked="agreed" />
            <text>我已阅读并同意</text>
            <text class="link" @click="showAgreement">《用户协议》</text>
            <text>和</text>
            <text class="link" @click="showPrivacy">《隐私政策》</text>
          </checkbox-group>
        </view>
        <text class="error" v-if="!agreed && showAgreementError">请同意用户协议和隐私政策</text>
      </view>

      <button 
        class="register-btn" 
        @click="handleRegister"
        :disabled="!formValid"
        :class="{ disabled: !formValid }"
      >
        注册
      </button>

      <view class="back-login">
        <text class="back-text" @click="goToLogin">已有账号？立即登录</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import Api from "@/utils/Api.js"

// 表单数据
const phone = ref('')
const password = ref('')
const confirmPassword = ref('')
const nickname = ref('')
const email = ref('')
const gender = ref(0)
const region = ref(['','',''])
const agreed = ref(false)
const showAgreementError = ref(false)

// 错误信息
const phoneError = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')
const nicknameError = ref('')
const emailError = ref('')

// 地区处理
const handleRegionChange = (e) => {
  region.value = e.detail.value || ['','','']
}

const getFormattedArea = () => {
  return region.value.filter(Boolean).join('') || ''
}

// 性别选择
const handleGenderChange = (value) => {
  gender.value = value
}

// 表单验证方法
const validateEmail = () => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!email.value.trim()) {
    emailError.value = '请输入邮箱'
    return false
  }
  if (!emailRegex.test(email.value)) {
    emailError.value = '请输入有效的邮箱地址'
    return false
  }
  emailError.value = ''
  return true
}

const validateForm = () => {
  const isValid = 
    validatePhone() & 
    validatePassword() & 
    validateConfirmPassword() & 
    validateNickname() & 
    validateEmail()
  return Boolean(isValid)
}

const validateNickname = () => {
  if (!nickname.value.trim()) {
    nicknameError.value = '请输入昵称'
    return false
  }
  if (nickname.value.trim().length > 20) {
    nicknameError.value = '昵称不能超过20个字符'
    return false
  }
  nicknameError.value = ''
  return true
}

const handleAgreementChange = (e) => {
  agreed.value = e.detail.value.length > 0
  showAgreementError.value = false
}

const formValid = computed(() => {
  return (
    /^1[3-9]\d{9}$/.test(phone.value) &&
    password.value.length >= 6 &&
    password.value === confirmPassword.value &&
    nickname.value.trim().length > 0 &&
    nickname.value.trim().length <= 20 &&
    /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value) &&
    agreed.value
  )
})

const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phone.value.trim()) {
    phoneError.value = '请输入手机号'
    return false
  }
  if (!phoneRegex.test(phone.value.trim())) {
    phoneError.value = '请输入正确的手机号'
    return false
  }
  phoneError.value = ''
  return true
}

const validatePassword = () => {
  if (!password.value.trim()) {
    passwordError.value = '请设置密码'
    return false
  } 
  if (password.value.trim().length < 6) {
    passwordError.value = '密码长度不能少于6位'
    return false
  }
  passwordError.value = ''
  return true
}

const validateConfirmPassword = () => {
  if (!confirmPassword.value.trim()) {
    confirmPasswordError.value = '请确认密码'
    return false
  } 
  if (confirmPassword.value.trim() !== password.value.trim()) {
    confirmPasswordError.value = '两次输入的密码不一致'
    return false
  }
  confirmPasswordError.value = ''
  return true
}

// 注册处理
const handleRegister = async () => {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单信息', icon: 'none' })
    return
  }
  
  if (!agreed.value) {
    showAgreementError.value = true
    uni.showToast({ title: '请同意用户协议', icon: 'none' })
    return
  }

  uni.showLoading({ title: '注册中...', mask: true })

  try {
    const params = {
      nickname: nickname.value.trim(),
      gender: gender.value,
      area: getFormattedArea(),
      email: email.value.trim(),
      phone: phone.value,
      password: password.value
    }

    // 修改后的请求处理方式
    const res = await new Promise((resolve, reject) => {
      uni.request({
        url: Api.domain + Api.register,
        method: 'POST',
        data: params,
        header: { 'Content-Type': 'application/json' },
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      })
    })

    // 处理响应
    if (res.statusCode === 200) {
      uni.showToast({
        title: res.data.msg || '注册成功',
        icon: 'success'
      })
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/login/login' })
      }, 1500)
    } else {
      throw new Error(res.data?.msg || `注册失败，错误码: ${res.statusCode}`)
    }
  } catch (error) {
    console.error('注册失败:', error)
    uni.showToast({
      title: error.message.includes('手机号') ? error.message : '注册失败，请稍后重试',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 跳转到登录页
const goToLogin = () => {
  uni.navigateTo({ url: '/pages/login/login' })
}

// 显示协议
const showAgreement = () => {
  uni.navigateTo({ url: '/pages/agreement/agreement' })
}

const showPrivacy = () => {
  uni.navigateTo({ url: '/pages/privacy/privacy' })
}
</script>


<style scoped>
.register-page {
  padding: 20px;
  background: linear-gradient(to bottom, #eaf6ff, #fff);
  min-height: 100vh;
  box-sizing: border-box;
}
.welcome {
  margin-top: 80px;
  margin-bottom: 17px;
  display: flex;
  flex-direction: column;
  padding-left: 15px;
}
.welcome .title {
  font-size: 25px;
  font-weight: bold;
  margin-bottom: 20px;
}
.welcome .subtitle {
  font-size: 15px;
  color: #1276ff;
}

.register-container {
  background-color: #fff;
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}

/* 表单样式 */
.form-section {
  margin-bottom: 20px;
}

.form-item {
  margin-bottom: 20px;
}

.label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.input {
  width: 100%;
  height: 44px;
  padding: 0 12px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  font-size: 15px;
  box-sizing: border-box;
  background-color: #fafafa;
}

.input:focus {
  border-color: #1276ff;
}

/* 地区选择器样式 */
.picker {
  width: 100%;
}

.picker-view {
  width: 100%;
  height: 44px;
  line-height: 44px;
  padding: 0 12px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  font-size: 15px;
  box-sizing: border-box;
  background-color: #fafafa;
  color: #666;
}

.error {
  display: block;
  margin-top: 6px;
  font-size: 12px;
  color: #f56c6c;
}

/* 协议样式 */
.agreement {
  display: flex;
  align-items: center;
  margin-top: 20px;
  font-size: 11.5px;
  color: #666;
  flex-wrap: wrap;
}

checkbox {
  margin-right: 3px;
}

.link {
  color: #1276ff;
  margin: 0 3px;
}

/* 按钮样式 */
.register-btn {
  width: 100%;
  height: 48px;
  line-height: 48px;
  background-color: #1276ff;
  color: #fff;
  border-radius: 6px;
  font-size: 16px;
  margin-top: 25px;
  border: none;
  transition: all 0.3s;
}

.register-btn:active {
  opacity: 0.8;
  transform: scale(0.98);
}

.register-btn.disabled {
  background-color: #c0c4cc;
  color: #fff;
  opacity: 0.7;
}

/* 返回登录 */
.back-login {
  margin-top: 20px;
  text-align: center;
}

.back-text {
  color: #1276ff;
  font-size: 14px;
}
</style>